const { createClient } = require('redis')
const dotenv = require('dotenv')

dotenv.config()

const client = createClient({
  url: process.env.REDIS_URL || 'redis://127.0.0.1:6379'
})

client.on('error', err => {
  console.error('Redis Client Error:', err)
  process.exit(1)
})

client.on('connect', () => console.log('Redis Connected'))
client.on('ready', () => console.log('Redis Ready'))

const connect = async () => {
  try {
    await client.connect()
  } catch (err) {
    console.error('Redis连接失败:', err)
    process.exit(1)
  }
}

// 确保在导出之前连接
connect()

// 存储验证码，设置5分钟过期
const setVerifyCode = async (email, code, type = 'default') => {
  const key = `verifyCode:${type}:${email}`;
  return await client.set(key, code, 'EX', 600); // 10分钟过期
}

// 获取验证码
const getVerifyCode = async (email, type = 'default') => {
  const key = `verifyCode:${type}:${email}`;
  return await client.get(key);
}

// 删除验证码
const deleteVerifyCode = async (email, type = 'default') => {
  const key = `verifyCode:${type}:${email}`;
  return await client.del(key);
}

module.exports = { setVerifyCode, getVerifyCode, deleteVerifyCode }
